<?php

trait Trait_Api_Tuan
{


    /**
     * 获取可预订日期
     * User: netman
     * Date: 2023/10/12 14:52
     */
    public function get_can_book_date($params)
    {
        $product_id = $params['product_id'];
        $row        = DB::select()->from('tuan')->where('id', '=', $product_id)->execute()->current();
        if (!$row['id']) {
            throw new Exception('未找到团购产品');
        } else {
            //非日历报价
            if ($row['price_type'] == 1) {
                $result = array(
                    'date' => date('Y-m-d'),
                    'price' => $row['price'],
                );
                return $result;
            } //日历报价
            else {
                if ($row['price_type'] == 2) {
                    $price  = DB::select()->from('tuan_price')
                        ->where('tuan_id', '=', $product_id)
                        ->and_where('day', '>=', strtotime(date('Y-m-d')))
                        ->and_where_open()
                        ->and_where('number', '=', '-1')
                        ->or_where('number', '>', 0)
                        ->and_where_close()
                        ->execute()
                        ->current();
                    $result = array(
                        'date' => date('Y-m-d', $price['day']),
                        'price' => $price['price']
                    );
                    return $result;
                } else {
                    return [];
                }
            }
        }
    }

    /**
     * 获取日历报价
     * @param $params
     * @return array|void
     * @throws Exception
     * User: netman
     * Date: 2023/10/12 15:02
     */
    public function get_calendar($params)
    {
        $product_id = $params['product_id'];

        $start_date = $params['start_date'] ? $params['start_date'] : '';
        $end_date   = $params['end_date'] ? $params['end_date'] : '';

        $row        = DB::select()->from('tuan')->where('id', '=', $product_id)->execute()->current();
        if (!$row['id']) {
            throw new Exception('未找到团购产品');
        } else {
            //非日历报价,读取3个月
            if ($row['price_type'] == 1) {
                $result = array();
                if (!($start_date && $end_date)) {
                    $start_date = strtotime(date('Y-m-d'));
                    $end_date   = strtotime(date('Y-m-d', strtotime("+3 month")));
                } else {
                    $start_date = strtotime($start_date);
                    $end_date   = strtotime($end_date);
                }

                //后台的团购时间限制
                $limit_endtime = $row['endtime'];
                $limit_starttime = $row['starttime'];

                $interval1 = [$start_date,$end_date];
                $interval2 = [$limit_starttime,$limit_endtime];
                if ($interval1[1] < $interval2[0] || $interval1[0] > $interval2[1]) {
                    $start = $start_date;
                    $end = $end_date;
                } else {
                    // 确定交集的起始点和结束点
                    $start = max($interval1[0], $interval2[0]);
                    $end = min($interval1[1], $interval2[1]);
                }

                for ($i = $start; $i <= $end; $i = $i + 86400) {
                    if ($row['totalnum'] > 0 || $row['totalnum'] == -1  ) {
                        $result[] = array(
                            'date' => date('Y-m-d', $i),
                            'price' => $row['price'],
                            'number' => $row['totalnum']
                        );
                    }
                }
                return $result;
            } //日历报价,获取所有报价
            else {
                if ($row['price_type'] == 2) {
                    $query = DB::select()->from('tuan_price')
                        ->where('tuan_id', '=', $product_id);
                    if ($start_date) {
                        $query->and_where('day', '>=', strtotime($start_date));
                    }
                    if ($end_date) {
                        $query->and_where('day', '<=', strtotime($end_date));
                    }
                    if (!$start_date && !$end_date) {
                        $query->and_where('day', '>=', strtotime(date('Y-m-d')));
                    }
                    $price_arr = $query->execute()->as_array();
                    $result    = array();
                    foreach ($price_arr as &$price) {
                        if ($price['number'] > 0 || $price['number'] == '-1') {
                            $result[] = array(
                                'date' => date('Y-m-d', $price['day']),
                                'price' => $price['price'],
                                'number' => $price['number']
                            );
                        }
                    }
                    return $result;
                }
            }
        }
    }

    /**
     * 获取快递费用
     * @param $params
     * @return array
     * User: netman
     * Date: 2023/10/12 15:08
     */
    public function get_express_fee($params)
    {
        $suit_id    = (int)$params['suit_id'];
        $address_id = (int)$params['address_id'];
        $dingnum    = (int)$params['ding_num'];
        $suit_info  = DB::select()->from('tuan')->where('id', '=', $suit_id)->execute()->current();
        $freight_id = $suit_info['freightid'];
        if (!empty($address_id)) {
            $plan_result = Model_Express_Plan::get_plan($freight_id, $address_id);
        } else {
            $province = $params['province'];
            $city     = $params['city'];
            if ($province && $city) {
                $plan_result = Model_Express_Plan::get_plan_by_address($freight_id, $province, $city);
            } else {
                $plan_result = array('status' => false);
            }
        }
        if ($plan_result['status'] == 0) {
            $result = array(
                'status' => false,
                'msg' => $plan_result['msg']
            );
        } else {
            $price  = Model_Express_Plan::get_freight_price($suit_info, $plan_result['data'], $dingnum);
            $result = array(
                'price' => $price,
                'express_plan_id' => $plan_result['data']['id'],
            );
        }
        return $result;
    }

    /**
     * @desc 属性生成where条件,用于多条件属性搜索
     * @param $attrid
     * @return string
     */
    private function get_attr_where($attrid)
    {
        $arr = Common::remove_arr_empty(explode('_', $attrid));
        foreach ($arr as $value) {
            $value = (int)$value;
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,sline_tuan.attrid) ";
            }
        }

        return $str;
    }

    /**
     * 格式化数据
     * @param $arr
     * @return array
     * User: netman
     * Date: 2023/10/12 13:45
     */
    private function format_tuan($arr, $mid = 0)
    {
        if(empty($arr)){
            return $arr;
        }
        // 获取营销策略
        $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance(self::TYPE_ID, array('mid'=> $mid));
        $out  = [];
        $time = time();
        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
        foreach ($arr as $v) {
            if(isset($uni_img[$v['id']])){
                $v['litpic'] = $uni_img[$v['id']];
            }
            $row              = [];
            $row['id']        = $v['id'];
            $row['title']     = $v['title'];
            $row['litpic']    = $this->img_url($v['litpic'], 750, 750);
            $row['price']     = $v['price']>0?Currency_Tool::price($v['price']):'';
            $row['sellprice'] = $v['sellprice']>0?Currency_Tool::price($v['sellprice']):'';
            $row['attr_list'] = Model_Tuan_Attr::get_attr_list($v['attrid']);
            if ($v['price'] > 0 && $v['sellprice'] > 0 && $v['sellprice'] > $v['price']) {
                $row['discount'] = $v['price'] == $v['sellprice'] ? '0' : bcmul(bcdiv($v['price'],$v['sellprice'],2),10);
            } else {
                $row['discount'] = 0;
            }
            $row['sellnum']   = Model_Member_Order::get_sell_num($v['id'], 13) + (int)$v['virtualnum'];
            $row['iconlist']  = Product::get_ico_list($v['iconlist']);
            $row['endtime']   = (int)$v['endtime'];
            $row['starttime'] = (int)$v['starttime'];
            //$v['jsendtime'] = date('Y/m/d H:i:s',$v['endtime']);
            //状态
            $row['status'] = $this->get_tuan_status($v);
            //倒计时时间,采用13位时间戳,需要*1000
            $row['count_time']   = ($v['starttime']>$time ? $v['starttime'] - $time : $v['endtime'] - $time) * 1000;
            $row['satisfyscore'] = St_Functions::get_satisfy(self::TYPE_ID, $v['id'], $v['satisfyscore'],
                array('suffix' => ''));
            $row['expire']       = ($v['starttime'] <= time() && $v['endtime'] >= time()) ? 0 : 1;
            $row['coming']       = $v['starttime'] > time() ? 1 : 0;
            // 营销策略
            $row['marketing_strategy'] = $marketing_strategy->get_support_application($row['id']);
            if($v['sellprice']){
                $discount = bcdiv($v['price'],$v['sellprice'],2);
                $discount = bcmul($discount,10,1);
                if ($discount == round($discount)) {
                    $row['discount'] = intval($discount); // 如果小数位是0，则转换为整数
                } else {
                    $row['discount'] = $discount;
                }
            }
            $out[]               = $row;
        }
        return $out;
    }

    /**
     * 获取团购产品的状态
     * @param $row
     * @return int
     */
    private function get_tuan_status($row)
    {
        //按状态 1：进行中 2：未开始 0 已过期 3,已售完
        $time = time();
        //已过期
        if ($row['endtime'] < $time) {
            return 0;
        } //进行中
        else {
            if ($row['starttime'] < $time && $time < $row['endtime']) {
                //检测是否卖完
                if ($row['price_type'] == 1 && $row['totalnum'] == 0) {
                    return 3;
                } else {
                    if ($row['price_type'] == 2) {
                        $totalnum = DB::select(DB::expr("sum(number) as total"))
                            ->from('tuan_price')
                            ->where('tuan_id', '=', $row['id'])
                            ->execute()
                            ->get('total');
                        if ($totalnum == 0) {
                            return 3;
                        }
                    }
                }
                return 1;
            } else {
                if ($time < $row['starttime']) {
                    return 2;
                }
            }
        }
    }

    /**
     * 获取内容详情
     * @param $params
     * @return array
     * User: netman
     * Date: 2023/10/12 13:59
     */
    private function get_detail_content($params)
    {
        $default = array(
            'typeid' => '13',
            'productinfo' => 0,
            'onlyrealfield' => 1,
            'pc' => 0

        );
        $params  = array_merge($default, $params);
        /**
         * @var array $productinfo
         */
        extract($params, true);
        $arr = DB::select()->from('tuan_content')
            ->where('webid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();

        //扩展表数据
        $product_id = $productinfo['id'];//产品id
        $ar        = DB::select()->from('tuan_extend_field')->where('productid', '=', $product_id)->execute()->as_array();
        $list      = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian') {
                continue;
            }
            if ($v['isrealfield'] == 1) {
                $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
                if (empty($content)) {
                    continue;
                }
            }
            $a                = array();
            $a['columnname']  = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];
            $a['content']     = Model_Api_V2_Xcx::filter_content($content);
            $list[]           = $a;
        }
        return $list;
    }

    /**
     * @param $params
     * @return array
     * @throws Exception
     */
    private function make_order($params)
    {
        $product_id = $params['product_id'];
        //收货地址
        $address_id  = $params['address_id'];
        $dingnum     = $params['ding_num'];
        $mid         = $params['mid'];
        $use_date    = $params['use_date'];
        $linkman     = $params['linkman'];
        $linktel     = $params['linktel'];
        $linkemail   = $params['linkemail'];
        $member_info = $params['member_info'];
        // 备注信息
        $remark = $params['remark'];
        //产品信息
        $info = DB::select()
            ->from('tuan')
            ->where('id', '=', $product_id)
            ->where('ishidden', '=', 0)
            ->and_where('status', '=', 3)
            ->execute()->current();
        if (!$info) {
            throw new Exception('当前产品已下架，不可预订');
        }
        //收货地址验证
        $receiver_address_id = 0;
        if ($mid) {
            $receiver_address_id = $address_id;
            if (!Model_Member_Address::check_address_id($mid, $receiver_address_id)) {
                $receiver_address_id = 0;
            }
        }

        // 快递计划
        $express_total_price = 0;
        $express_plan_id     = (int)$params['express_plan_id'];
        if (!empty($info['freightid']) && $info['receive_address'] == 1) {
            $plan_info = null;
            if ($mid) {
                $plan_info = Model_Express_Plan::get_plan($info['freightid'], $receiver_address_id);
            }
            if ($plan_info['status'] == 0 || $plan_info['data']['id'] != $express_plan_id) {
                throw new Exception('快递信息有误');
            }
            $express_price       = Model_Express_Plan::get_freight_price($info, $plan_info['data'], $dingnum);
            $express_total_price = floatval($express_price);
        }

        $current_time = time();
        if ($current_time < $info['starttime'] || $current_time > $info['endtime']) {
            throw new Exception('当前产品已过期或失效,暂不能预订,请联系客服!');
        }

        //限购判断
        $buy_num_limit = $this->get_buy_num_limit($info['id'], $info['limit_order'], $mid, $use_date);
        if ($buy_num_limit <= 0) {
            throw new Exception('已达到购买上限,暂不能预订,请联系客服!');
        }


        // 检查联系人和联系电话
        if (!$linkman || !$linktel) {
            throw new Exception('请填写联系人信息!');
        }


        //积分抵现.
        $needJifen   = $params['needjifen'];
        $jifentprice = 0;
        $useJifen    = 0;
        if ($needJifen) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($info['jifentprice_id'], self::TYPE_ID, $needJifen,
                $member_info);
            $useJifen    = empty($jifentprice) ? 0 : 1;
            $needJifen   = empty($jifentprice) ? 0 : $needJifen;
        }
        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $jifencomment      = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];
        if ($receiver_address_id) {
            $receiver_address_info      = DB::select('province', 'city', 'area', 'receiver', 'phone', 'postcode',
                'address')->from('member_address')
                ->where('id', '=', $receiver_address_id)->execute()->current();
            $receiver_address_info_json = json_encode($receiver_address_info, JSON_UNESCAPED_UNICODE);
        }

        // 订单数据
        $order = array(
            'litpic' => $info['litpic'],
            'typeid' => self::TYPE_ID,
            'productautoid' => $product_id,
            'productaid' => $info['aid'],
            'productname' => $info['title'],
            'departdate' => '',
            'webid' => 0,
            'addtime' => time(),
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => $linkemail,
            'remark' => $remark,
            'usejifen' => $useJifen,
            'needjifen' => $needJifen,
            'jifentprice' => $jifentprice,
            'jifenbook' => $info['jifenbook_id'],
            'jifencomment' => $jifencomment,
            'memberid' => $mid,
            'suitid' => 0,
            'childnum' => 0,
            'oldnum' => 0,
            'people4_num' => 0,
            'people5_num' => 0,
            'people6_num' => 0,
            'roombalancenum' => 0,
            'roombalance_paytype' => 1,
            'receiver_address_id' => $receiver_address_id,
            'receiver_address_infos' => $receiver_address_info_json ? $receiver_address_info_json : '',
            'express_total_price' => $express_total_price,
        );

        //成人数量
        if ($dingnum) {
            $order['dingnum'] = $dingnum;
        }

        //自动关闭订单时间
        $auto_close_time = $info['auto_close_time'] ? $info['auto_close_time'] : 0;
        if ($auto_close_time) {
            $order['auto_close_time'] = $auto_close_time + time();
        }

        $auto_confirm_time = $info['auto_confirm_time'] ?: 0;
        if ($auto_confirm_time) {
             $order['auto_confirm_time']= $auto_confirm_time + time();
        }

        //自动退款时限
        $use_date=trim($params['use_date']);
        $no_confirm_refund = $info['no_confirm_refund'] ?: 0;
        if ($no_confirm_refund) {
            $order['no_confirm_refund'] = strtotime($use_date . ' +1 day') -  $no_confirm_refund ;
        }
        //收货地址
        if ($address_id) {
            $order['receiver_address_id'] = $address_id;
        }
        //出发日期
        if ($use_date) {
            $order['usedate'] = $use_date;
        }

        //日历 or 普通报价
        if ($info['price_type'] == 1) {
            $price = $info['price'];
        } else {
            if ($info['price_type'] == 2) {
                $row   = DB::select('price')->from('tuan_price')
                    ->where('tuan_id', '=', $product_id)
                    ->and_where('day', '=', strtotime($use_date))
                    ->execute()
                    ->current();
                $price = $row['price'];
            }
        }

        // 二次确认支付
        $order['status']             = $info['paytype'] == 3 ? 0 : 1;
        $order['paytype']            = $info['paytype'];
        $order['dingjin']            = doubleval($info['dingjin']);
        $order['price']              = $price;
        $order['childprice']         = 0;
        $order['oldprice']           = 0;
        $order['people4_price']      = 0;
        $order['people5_price']      = 0;
        $order['people6_price']      = 0;
        $order['roombalance']        = 0;
        $order['suit_name']          = '';
        $order['refund_restriction'] = $info['refund_restriction'];

        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $order['source'] = $params['source'];

        return array(
            'status' => true,
            'data' => $order,
            'msg' => ''
        );
    }

    /**
     * 限购判断
     * @param $tuan_id
     * @param $limit_order
     * @param $mid
     * @param $usedate
     * @return int|mixed
     * User: netman
     * Date: 2023/10/12 15:30
     */
    private function get_buy_num_limit($tuan_id, $limit_order, $mid, $usedate)
    {
        $info = DB::select()->from('tuan')->where('id', '=', $tuan_id)->execute()->current();
        if ($info['price_type'] == 1) {
            // 0 不限购 预定数量为产品数量
            if ($limit_order == '0') {
                $totalnum      = DB::select('totalnum')->from('tuan')->where('id', '=',
                    $tuan_id)->execute()->get('totalnum');
                $buy_num_limit = $totalnum == -1 ? 1000 : $totalnum;
            } else {
                $bought_num    = Model_Tuan::get_bought_num($mid, null, $tuan_id);
                $buy_num_limit = intval($limit_order) - $bought_num;
            }
        } //日历
        else {
            if ($info['price_type'] == 2) {
                $day = strtotime($usedate);
                // 0 不限购 预定数量为产品数量
                if ($limit_order == '0') {
                    $totalnum      = DB::select('number')->from('tuan_price')
                        ->where('tuan_id', '=', $tuan_id)
                        ->and_where('day', '=', $day)
                        ->execute()->get('number');
                    $buy_num_limit = $totalnum == '-1' ? 99999 : $totalnum;
                } else {
                    $bought_num    = Model_Tuan::get_bought_num($mid, null, $tuan_id);
                    $buy_num_limit = intval($limit_order) - $bought_num;
                }
            }
        }
        return $buy_num_limit;
    }

}